'''
Created on Dec 7, 2009

@author: wangjo
'''
import os
import re
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import logging

DEBUG = True
DEFAULT_LIMIT = 24

class BaseRequestHandler(webapp.RequestHandler):
    def rssgenerate(self, template_name, template_values = {}):
        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.generate(template_name, template_values, detectmb = False)
        
    def generate(self, template_name, template_values = {}):
        logging.info('base output method')
        values = {
            'request' : self.request,
            'user' : users.get_current_user(),
            'is_admin': users.is_current_user_admin(),
            'login_url': users.create_login_url(self.request.uri),
            'logout_url': users.create_logout_url('http://%s/' % (self.request.host,)),
            'application_name' : 'CBN Channel',
        }
        logging.info('user-agent:%s'%self.request.headers['User-Agent'])
        values.update(template_values)
        dir = os.path.dirname(__file__)
        path = os.path.join(dir, os.path.join('templates', template_name)) 
        self.response.out.write(template.render(path, values))
        
    def pageHandler(self):
        page = self.request.get('page', None)
        if not page or int(page) < 1:
            page = 1
        else:
            page = int(page)
        return page
    
    def limitHandler(self):
        limit = self.request.get('limit', None)
        if not limit or int(limit) < 1:
            limit = DEFAULT_LIMIT
        else:
            limit = int(limit)
        logging.debug('limit: %d'%limit)
        return limit
        
class MultipleOutputRequestHandler(BaseRequestHandler):
    _OUTPUT_TYPES = {
            'default': ['text/html', 'html'],
            'html': ['text/html', 'html'],
            'atom': ['application/atom+xml', 'xml'],
            'json': ['application/javascript', 'json'],
            }
    def multiplegen(self, template_name, template_values = {}):
        output_name = self.request.get('output')
        if output_name not in self._OUTPUT_TYPES:
            output_name = 'default'
        output_type = self._OUTPUT_TYPES[output_name]
        self.response.headers['Content-Type'] = output_type[0]
        template_name = '%s.%s' % (template_name, output_type[1])
        self.generate(template_name, template_values)
        